package com.ycsj.goldmedalnewconcept.student.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.suke.widget.SwitchButton;
import com.ycsj.common.base.BaseLazyFragment;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.base.SpKeys;
import com.ycsj.common.image.ImageUtil;
import com.ycsj.common.manager.CacheDataManager;
import com.ycsj.common.manager.PopUpManager;
import com.ycsj.common.utils.ExitLogonUtil;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.NotificationsUtils;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.UIHelper;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.activity.AboutUsActivity;
import com.ycsj.goldmedalnewconcept.common.activity.HelpActivity;
import com.ycsj.goldmedalnewconcept.common.activity.NoticeActivity;
import com.ycsj.goldmedalnewconcept.common.activity.VerionInfoActivity;
import com.ycsj.goldmedalnewconcept.common.bean.CodeInfo;
import com.ycsj.goldmedalnewconcept.common.bean.UnNoticeItem;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.ExitPopUtils;
import com.ycsj.goldmedalnewconcept.common.util.StateCodeUtils;
import com.ycsj.goldmedalnewconcept.main.activity.AgreementAndPrivacyActivity;
import com.ycsj.goldmedalnewconcept.main.activity.ChooseRoleActivity;
import com.ycsj.goldmedalnewconcept.student.activity.MyCollectionListActivity;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 学生端我的Fragment
 * Created by Administrator on 2019/2/19 0019.
 */

public class StudentMeFragment extends BaseLazyFragment implements SwitchButton.OnCheckedChangeListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;

    @BindView(R.id.switch_notice_button)
    SwitchButton switchNoticeButton;
    //缓存大小的文本
    @BindView(R.id.tv_cach_size)
    TextView tvCachSize;
    //清除缓存
    @BindView(R.id.ll_clean)
    RelativeLayout llClean;
    @BindView(R.id.ll_out)
    RelativeLayout llOut;
    //头像
    @BindView(R.id.iv_head)
    RoundedImageView ivHead;
    //姓名
    @BindView(R.id.tv_name)
    TextView tvName;
    //账号
    @BindView(R.id.tv_acc)
    TextView tvAcc;
//    //官方网站
//    @BindView(R.id.rl_website)
//    RelativeLayout rlWebsite;

    //我的收藏
    @BindView(R.id.rl_collection)
    RelativeLayout rlCollection;

    //关于我们
    @BindView(R.id.rl_about)
    RelativeLayout rl_about;

    //隐私政策
    @BindView(R.id.rl_yszc)
    RelativeLayout rl_yszc;

    //用户协议
    @BindView(R.id.rl_yhxy)
    RelativeLayout rl_yhxy;


    //注销账户
    @BindView(R.id.rl_zxzh)
    RelativeLayout rl_zxzh;


    //公告
    @BindView(R.id.rl_notice)
    RelativeLayout rl_notice;

    //校区
    @BindView(R.id.tv_school)
    TextView tv_school;

    //版本
    @BindView(R.id.rl_version)
    RelativeLayout rl_version;

    //帮助与反馈
    @BindView(R.id.rl_help)
    RelativeLayout rl_help;

    //公告未读数
    @BindView(R.id.tv_un_count)
    TextView tv_un_count;


    //是否需要跳转的标识
    private boolean isNeeded = true;


    //记录官网地址
    private String url;

    //更新缓存大小的标识
    public static final int UPDATECACHESIZE = 0x230;

    public static final String TAG = StudentMeFragment.class.getName();

    //单体模式
    private static class LazyHolder {
        private static final StudentMeFragment INSTANCE = new StudentMeFragment();
    }

    public static final StudentMeFragment newInstance() {
        return LazyHolder.INSTANCE;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_me;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

    }

    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);

        //初始化标题栏
        initTitle();

        //设置默认的缓存大小
        initState();

        //设置数据
        initData();

        //获取公告未读数
        http();
    }

    /**
     * 获取公告未读数
     */
    private void http() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "45");
        map.put("c", AccountUtils.getAccount(getActivity()));
        map.put("role", AccountUtils.getRole(getActivity()));

        HttpUtils.post(HttpAddress.UNNOTICE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {

                if (!TextUtils.isEmpty(response)) {
                    UnNoticeItem info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, UnNoticeItem.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }
                    if (null != info) {
                        if ("1".equals(info.getState())) {

                            //返回成功
                            //头像和姓名
                            tvName.setText(info.getF_name());

                            //设置账号
                            tvAcc.setText("账号：" + AccountUtils.getAccount(getActivity()));

                            //设置校区名称
                            tv_school.setText(info.getF_schoolname());

                            //设置头像
                            ImageUtil.displayImage(getContext(), ivHead, info.getF_icon()
                                    , R.drawable.base_def_headimg);

                            //头像和姓名
                            tvName.setText(info.getF_name());

                            //设置账号
                            tvAcc.setText("账号：" + AccountUtils.getAccount(getActivity()));

                            //设置校区名称
                            tv_school.setText(info.getF_schoolname());

                            //设置头像
                            ImageUtil.displayImage(getContext(), ivHead, info.getF_icon()
                                    , R.drawable.base_def_headimg);

                            //更新ShoolID
                            SPUtil.put(getContext(), SpKeys.SCHOOLID, info.getF_schoolid());

                            //返回成功
                            if ("0".equals(info.getUnread_count()) || TextUtils.isEmpty(info.getUnread_count())) {
                                tv_un_count.setVisibility(View.GONE);
                            } else {
                                tv_un_count.setVisibility(View.VISIBLE);
                                tv_un_count.setText(info.getUnread_count());
                            }

                            //记录官网地址
                            url = info.getApp_url();

                            LogUtils.iTag("test", "返回的地址是:" + url);

                            //保存LOGO
                            SPUtil.put(getContext(), SpKeys.LOGO, info.getApp_logo());

                        } else {
                            tv_un_count.setVisibility(View.GONE);
                        }
                    }
                }
            }
        });
    }

    /**
     * 初始化标题栏的方法
     */
    private void initTitle() {
        ivBack.setVisibility(View.INVISIBLE);
        tvTitle.setText("我 的");
    }


    /**
     * 初始化标题栏的方法
     */
    private void initData() {

        //设置姓名
        tvName.setText(AccountUtils.getName(getActivity()));

        //设置账号
        tvAcc.setText("账号：" + AccountUtils.getAccount(getActivity()));

        //设置校区名称
        tv_school.setText(AccountUtils.getSchoolName(getActivity()));

        //设置头像
        ImageUtil.displayImage(getContext(), ivHead, AccountUtils.getIcon(getContext())
                , R.drawable.base_def_headimg);
    }

    /**
     * 设置初始状态
     */
    private void initState() {

        //设置显示缓存大小的TextView
        try {
            tvCachSize.setText("(" + CacheDataManager.getTotalCacheSize(getActivity()) + ")");
        } catch (Exception e) {
            e.printStackTrace();
        }

        switchNoticeButton.setOnCheckedChangeListener(this);
    }


    /**
     * 弹出退出登录的弹框
     */
    private void showExitPop() {

        ExitPopUtils.showExitPop(getContext(), getActivity(), new ExitPopUtils.OnExitListener() {
            @Override
            public void onExitOk() {
                //退出的相关操作,清空SP的相关数据
                ExitLogonUtil.exitLogin(getActivity());

                //关闭当前页面
                getActivity().finish();
                UiUtils.startActivity(getActivity(), ChooseRoleActivity.class);
            }
        });
    }

    /**
     * 开关按钮的监听事件
     *
     * @param view
     * @param isChecked
     */
    @Override
    public void onCheckedChanged(SwitchButton view, boolean isChecked) {

        //点关闭时,这个时候通知状态是true,开关状态是false   切回来的时候通知状态还是true,开关状态同步为true
        isNeeded = isChecked != NotificationsUtils.isOpenNotification(getActivity());

        if (isNeeded) {
            //需要跳转界面
            NotificationsUtils.startSysSettingActivity(getActivity());
        }
    }

    /**
     * 弹出清除缓存的弹框
     */
    private void showCleanPop() {
        try {
            if ("0.0B".equals(CacheDataManager.getTotalCacheSize(getActivity()))) {
                //证明无缓存需要清理
                UIHelper.showToast(getActivity(), "暂无缓存需要清理");
            } else {
//                AlertDialogUtil.showAlertDialog(true, getActivity(), "确定清除所有本地缓存吗?", new AlertDialogUtil.onListener() {
//                    @Override
//                    public void onClickOk() {
//                        //清除缓存
//                        cleanCache();
//                    }
//
//                    @Override
//                    public void onClickDismiss() {
//
//                    }
//                });

                showCleanCachePop();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除缓存的方法
     */
    private void cleanCache() {
        new Thread(new clearCache()).start();
    }

    /**
     * 处理清除缓存消息的Handler对象
     */
    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                UIHelper.showToast(getActivity(), "清除缓存成功");

                try {
                    if ("0.0B".equals(CacheDataManager.getTotalCacheSize(getActivity()))) {
                        tvCachSize.setText("(0.00M)");
                    } else {
                        tvCachSize.setText("( " + CacheDataManager.getTotalCacheSize(getActivity()) + " )");

                    }

                } catch (Exception e) {

                    e.printStackTrace();
                }
            }
        }
    };

    /**
     * 实现清除缓存的Runnable
     */
    class clearCache implements Runnable {

        @Override

        public void run() {

            try {

                CacheDataManager.clearAllCache(getActivity());

                Thread.sleep(300);

                if (CacheDataManager.getTotalCacheSize(getActivity()).startsWith("0")) {

                    handler.sendEmptyMessage(0);

                }

            } catch (Exception e) {

            }
        }
    }

    /**
     * 页面控件的点击事件
     *
     * @param v
     */
    @OnClick({R.id.ll_clean, R.id.rl_collection, R.id.rl_notice, R.id.rl_about, R.id.ll_out, R.id.rl_help, R.id.rl_version, R.id.rl_zxzh, R.id.rl_yszc, R.id.rl_yhxy})
    public void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.ll_clean:
                //清除缓存
                showCleanPop();
                break;
            // R.id.rl_website,
//            case R.id.rl_website:
//                //官方网站
//                GuanwangActivity.goActivity(getContext(), url);
//                break;
            case R.id.rl_notice:
                //清除未读
                tv_un_count.setText("");
                tv_un_count.setVisibility(View.GONE);
                //公告
                UiUtils.startActivity(getActivity(), NoticeActivity.class);
                break;
            case R.id.rl_about:
                //关于
                UiUtils.startActivity(getContext(), AboutUsActivity.class);
                break;
            case R.id.rl_yszc:
                //隐私政策
                AgreementAndPrivacyActivity.goActivity(getContext(), "隐私政策");
                break;
            case R.id.rl_yhxy:
                //用户协议
                AgreementAndPrivacyActivity.goActivity(getContext(), "用户协议");
                break;
            case R.id.rl_zxzh:
                //注销用户
                doAnsubscribeAction();
                break;
            case R.id.ll_out:
                //退出登录
                showExitPop();
                break;
            case R.id.rl_help:
                //帮助与反馈
                UiUtils.startActivity(getActivity(), HelpActivity.class);
                break;
            case R.id.rl_version:
                //版本介绍
                UiUtils.startActivity(getActivity(), VerionInfoActivity.class);
                break;
            case R.id.rl_collection:
                //我的收藏
                MyCollectionListActivity.goActivity(getContext());
                break;
        }
    }


    /**
     * 注销用户的操作
     */
    private void doAnsubscribeAction() {
        PopUpManager.showPopByMatchParent(getContext(), R.layout.pop_unsubscribe_account, 0.3f, getActivity(), new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                Button bt_qx = view.findViewById(R.id.btn_neg);
                Button bt_qd = view.findViewById(R.id.btn_pos);
                bt_qx.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PopUpManager.dismiss();
                    }
                });

                bt_qd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 请求服务器进行注销账号的操作
                        Map<String, String> map = new HashMap<>();
                        map.put("type", "11");
                        map.put("platform", "8");
                        map.put("acc", AccountUtils.getAccount(getActivity()));
                        map.put("role", AccountUtils.getRole(getActivity()));
                        HttpUtils.post(HttpAddress.UNSUB_ACCOUNT, map, StudentMeFragment.this, new HttpUtils.CallBack() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                PopUpManager.dismiss();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                if (!TextUtils.isEmpty(response)) {
                                    PopUpManager.dismiss();
                                    CodeInfo res = GsonUtil.jsonToBean(response, CodeInfo.class);
                                    if ("200".equals(res.state)) {

                                        //接口请求成功后返回登录界面
                                        ToastUtils.showShort("账号注销成功");

                                        new Handler().postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                //退出的相关操作,清空SP的相关数据
                                                ExitLogonUtil.exitLogin(getActivity());
                                                //关闭当前页面
                                                getActivity().finish();
                                                UiUtils.startActivity(getActivity(), ChooseRoleActivity.class);
                                            }
                                        }, 1000);

                                    } else if ("-1".equals(res.state)) {

                                        ToastUtils.showShort("执行失败,账号注销失败");

                                    } else if ("103".equals(res.state)) {

                                        StateCodeUtils.showSateCode("103");
                                    }
                                }
                            }
                        });

                    }
                });
            }
        });
    }

    /**
     * 切换到该界面时再次统计缓存大小
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && UPDATECACHESIZE == busInfo.type) {
            //再次设置缓存的大小
            initState();
        }
    }

    /**
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            //显示状态
            http();
        }
    }


    /**
     * 弹出跳转的PopUpWindow
     */
    private void showCleanCachePop() {
        PopUpManager.showPopByMatchParent(getContext(), R.layout.pop_clean_caches, 0.3f, getActivity(), new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                TextView tv_again = view.findViewById(R.id.tv_again);
                TextView tv_over = view.findViewById(R.id.tv_over);
                tv_again.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            //取消
                            PopUpManager.dismiss();
                        }

                    }
                });

                tv_over.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            //确定
                            PopUpManager.dismiss();
                            //清除缓存
                            cleanCache();
                        }

                    }
                });

            }
        });
    }
}
